package logic

import (
	"context"

	"github.com/eeppee_admin/clouddisk/service/internal/svc"
	"github.com/eeppee_admin/clouddisk/service/internal/types"
	"github.com/eeppee_admin/clouddisk/service/model"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserFileDeleteLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserFileDeleteLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserFileDeleteLogic {
	return &UserFileDeleteLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserFileDeleteLogic) UserFileDelete(req *types.UserFileDeleteRequest, userIdentity string) (resp *types.UserFileDeleteResponse, err error) {
	sp := new(model.StorePool)
	_, err = l.svcCtx.Engine.
		Where("size").
		Where("identity = (select store_identity from userstore where identity = ? limit 1)", req.Identity).
		Get(sp)
	if err != nil {
		logx.Error(err)
		return
	}
	// 更新当前容量
	if sp.Size > 0 {
		_, err = l.svcCtx.Engine.Exec("update user set new_volume = new_volume - ? where identity = ?", sp.Size, userIdentity)
		if err != nil {
			logx.Error(err)
			return
		}
	}

	// 删除用户数据
	_, err = l.svcCtx.Engine.Where("user_identity = ? and identity = ?", userIdentity, req.Identity).
		Delete(new(model.UserStore))
		
	return
}
